package com.shop.cereshop.app.job;

import com.shop.cereshop.app.service.product.ProductAveragePriceService;
import com.shop.cereshop.app.service.shop.LabelCalculationService;
import com.shop.cereshop.commons.domain.calculate.Calculate;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import groovy.util.logging.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 商品均价计算任务
 */
@Component
@Slf4j
public class ProductAvgPriceJob {

    @Resource
    private ProductAveragePriceService productAveragePriceService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    LabelCalculationService labelCalculationService;

    /**
     * 1、计算店铺均价
     */
    @XxlJob("calculateProductAveragePrice")
    public void calculateProductAveragePrice() throws Exception {
        XxlJobHelper.log("开始计算商品均价");
        productAveragePriceService.calculateProductAveragePrice();
    }

    /**
     * 2、处理店铺相关的标签
     */
    @XxlJob("shopTitle")
    @Scheduled(fixedDelay = 1000 * 60 )
    public void shopTitle() throws Exception {
        System.out.println("开始 处理店铺相关的标签");
        List<Calculate> shopCalculates = labelCalculationService.shopTitleCalculation();
        Map<Long, List<Calculate>> collect = shopCalculates.stream().collect(Collectors.groupingBy(Calculate::getShopId));
        // 处理每个店铺的标签数据
        collect.keySet().forEach(shopId -> {
            redisTemplate.opsForHash().put("shop", String.valueOf(shopId), collect.get(shopId).get(0));
        });
    }

    /**
     * 3.处理商品相关的标签
     */
    @Scheduled(fixedDelay = 1000 * 60 )
    @XxlJob("productTitle")
    public void productTitle() throws Exception {
        System.out.println("开始 处理商品相关的标签");
        List<Calculate> productCalculates = labelCalculationService.productTitleCalculation();
        Map<Long, List<Calculate>> collect = productCalculates.stream().collect(Collectors.groupingBy(Calculate::getProductId));
        collect.keySet().forEach(productId -> {
            redisTemplate.opsForHash().put("product", String.valueOf(productId), collect.get(productId).get(0));

        });
    }


}



